# zbx_itemctl/zbx_itemctl/item_service.py
from typing import Any, Dict, List
from .client import ZabbixClient

class ItemService:
    def __init__(self, client: ZabbixClient):
        self.cli = client

    def list_items(self, hostid: str = None, key_: str = None) -> List[Dict[str, Any]]:
        params = {"output": ["itemid", "name", "key_", "type", "value_type", "delay"]}
        if hostid:
            params["hostids"] = [hostid]
        if key_:
            params["search"] = {"key_": key_}
        return self.cli.call("item.get", params)

    def create_item(
        self,
        hostid: str,
        name: str,
        key_: str,
        type_: int = 0,
        value_type: int = 3,
        delay: str = "30s",
    ) -> str:
        # 自动查找接口 ID
        hosts = self.cli.call(
            "host.get",
            {
                "hostids": [hostid],
                "selectInterfaces": ["interfaceid", "type"],
            },
        )
        if not hosts or not hosts[0]["interfaces"]:
            raise RuntimeError(f"Host {hostid} 没有任何接口")
        interfaceid = next(
            i["interfaceid"]
            for i in hosts[0]["interfaces"]
            if int(i["type"]) == 1  # 1 = agent
        )

        params = {
            "hostid": hostid,
            "name": name,
            "key_": key_,
            "type": type_,
            "value_type": value_type,
            "delay": delay,
            "interfaceid": interfaceid,
        }
        result = self.cli.call("item.create", [params])
        return result["itemids"][0]

    def list_hosts(self) -> List[Dict[str, Any]]:
        params = {"output": ["hostid", "host", "name"]}
        return self.cli.call("host.get", params)